package com.cyf.gongbeigate.utils

import javax.servlet.http.HttpServletRequest
import org.apache.commons.fileupload.disk.DiskFileItemFactory
import javax.servlet.ServletContext
import org.apache.commons.fileupload.servlet.ServletFileUpload
import java.util.HashMap
import org.apache.commons.fileupload.FileItem
import com.cyf.gongbeigate.utils.FileUploadUtils
import org.apache.commons.fileupload.FileUploadException
import java.io.File
import java.util.UUID
import java.lang.Exception
import java.io.UnsupportedEncodingException

object FileUploadUtils {
    fun parseRequest(req: HttpServletRequest): Map<String, Any> {
        val diskFileItemFactory = DiskFileItemFactory()
        val servletContext = req.servletContext
        val repository = servletContext.getAttribute("javax.servlet.context.tempdir") as File
        diskFileItemFactory.repository = repository
        val upload = ServletFileUpload(diskFileItemFactory)
        upload.headerEncoding = "utf-8"
        val map: MutableMap<String, Any> = HashMap()
        try {
            val items = upload.parseRequest(req)
            val iterator: Iterator<FileItem> = items.iterator()
            while (iterator.hasNext()) {
                val item = iterator.next()
                if (item.isFormField) {
                    processFormField(item, map)
                } else {
                    processFileUpload(req, item, map)
                }
            }
        } catch (e: FileUploadException) {
            e.printStackTrace()
        }
        return map
    }

    private fun processFileUpload(req: HttpServletRequest, item: FileItem, map: MutableMap<String, Any>) {
        val fieldName = item.fieldName
        var fileName = item.name
        fileName = UUID.randomUUID().toString() + "-" + fileName
        val hashCode = fileName.hashCode()
        val hex = Integer.toHexString(hashCode)
        val chars = hex.toCharArray()
        var base = ""
        for (_char in chars) {
            base = "$base/$_char"
        }
        fileName = "$base/$fileName"
        val upload = req.servletContext.getRealPath("post_img")
        val file = File("$upload/$fileName")
        if (!file.parentFile.exists()) {
            file.parentFile.mkdirs()
        }
        try {
            item.write(file)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        map[fieldName] = fileName
    }

    private fun processFormField(item: FileItem, map: MutableMap<String, Any>) {
        val fieldName = item.fieldName
        try {
            val value = item.getString("utf-8")
            map[fieldName] = value
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }
    }
}